<script lang="jsx" setup>
import { computed, ref } from 'vue';
import { useRoute } from 'vue-router';
import { AppstoreOutlined, UnorderedListOutlined } from '@ant-design/icons-vue';
import { UUID } from 'uuidjs';
import { useElementSize } from '@vueuse/core';
import { getImgList } from '@/service/api/modules/trace/aoi';
import { useRouterPush } from '@/hooks/common/router';
import { useTabStore } from '@/store/modules/tab';
import { useRouteStore } from '@/store/modules/route';
import Modal from '@/components/common/modal.vue';

const { routerPushByKey } = useRouterPush();
const tabStore = useTabStore();
const routeStore = useRouteStore();
const route = useRoute();

async function closePage() {
  const path = route.fullPath;
  const tab = tabStore.tabs.find(item => {
    if (item.fullPath === path) {
      return item;
    }
  });
  await tabStore.removeTab(tab.id);
  await routerPushByKey('trace_aoi-trace');
  await routeStore.reCacheRoutesByKey(tab.routeKey);
}

const showType = ref('list');
const imgList = ref([]);
const viewImgList = ref([]);
const imgContentRef = ref(null);
// 分页相关
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(200);
const pageSizeOptions = ref(['200', '500', '1000', '2000']);
const columns = [
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    fixed: 'left',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'fileName',
    dataIndex: 'fileName',
    title: '文件名称',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'size',
    dataIndex: 'size',
    title: '文件大小',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'time',
    dataIndex: 'time',
    title: '时间',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'url',
    dataIndex: 'url',
    title: '图片',
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      return (
        <div class="flex-center">
          <img
            width={22}
            v-lazy={record.url}
            alt=""
            key={record.url}
            onClick={() => handleViewImg(record.dataIndex - 1)}
          />
        </div>
      );
    }
  }
];
function getList() {
  getImgList().then(({ data, error }) => {
    if (!error) {
      console.log(data);
      // 过滤不是图片的类型

      imgList.value = data
        .filter(item => {
          const type = item.split('.')[1];
          return type === 'jpeg' || type === 'png' || type === 'gif' || type === 'jpg';
        })

        .map(item => {
          return {
            fileName: item,
            url: `http://192.168.134.22:9207/one-code-fileReader/${item}`,
            size: '1.2M',
            time: '2022-03-18 10:00:00'
          };
        });
      imgList.value.forEach((item, index) => {
        item.dataIndex = index + 1;
        item.tableUuid = UUID.genV4().hexNoDelim;
      });
      total.value = data.length;
      pageSizeOptions.value.push(data.length.toString());
      viewImgList.value = imgList.value.map(item => item.url);
    }
  });
}
getList();

function onChange(page, pageSizes) {
  pageNum.value = page;
  pageSize.value = pageSizes;
  imgContentRef.value.scrollTop = 0;
}

function typeChange() {
  pageNum.value = 1;
}

const computedList = computed(() => {
  // 计算起始索引
  const startIndex = (pageNum.value - 1) * pageSize.value;
  // 计算结束索引
  const endIndex = startIndex + pageSize.value;

  // 截取出当前页的数据
  const paginatedData = imgList.value.slice(startIndex, endIndex);

  return paginatedData;
});

// 预览图片
const viewImgVisible = ref(false);
const currentImgViewIndex = ref(0);
const imgScale = ref(1);
const rotate = ref(0);
function handleViewImg(index) {
  viewImgVisible.value = true;
  currentImgViewIndex.value = index;
}

function handleNext() {
  if (currentImgViewIndex.value === imgList.value.length - 1) return;
  resetStyle();
  currentImgViewIndex.value += 1;
}

function handleImgPreviou() {
  if (currentImgViewIndex.value === 0) return;
  resetStyle();
  currentImgViewIndex.value -= 1;
}

function resetStyle() {
  imgScale.value = 1;
  rotate.value = 0;
}

function handleScale(type) {
  if (type === 'plus') {
    imgScale.value += 0.1;
  } else {
    imgScale.value -= 0.1;
  }
}

function handleScroll(event) {
  event.stopPropagation();
  if (event.deltaY < 0) {
    // 向上滚动放大
    imgScale.value += 0.1;
  } else {
    // 向下滚动缩小
    imgScale.value -= 0.1;
  }
}

function handleRotate(type) {
  if (type === 'left') {
    rotate.value -= 90;
  } else {
    rotate.value += 90;
  }
}

function handleViewImgClose() {
  viewImgVisible.value = false;
  resetStyle();
}

const { height } = useElementSize(imgContentRef);

const tableScrollY = computed(() => {
  return height.value - 98;
});
</script>

<template>
  <div class="aoi-img-page jl-main-page h-full w-full">
    <div class="top">
      <div class="show-type">
        <div class="lable">
          <span>显示形式:</span>
        </div>
        <ARadioGroup v-model:value="showType" @change="typeChange">
          <ARadioButton value="list">
            <AppstoreOutlined />
          </ARadioButton>
          <ARadioButton value="table">
            <UnorderedListOutlined />
          </ARadioButton>
        </ARadioGroup>
      </div>
      <div class="colose-btn">
        <AButton type="primary" ghost class="mini-btn mr-8px" @click="closePage">
          <template #icon>
            <icon-ic-round-close class="align-sub text-icon" />
          </template>
          <span class="ml-3px">关闭</span>
        </AButton>
      </div>
    </div>

    <!-- 图片列表 -->
    <div ref="imgContentRef" class="img-content w-full">
      <div v-if="showType === 'list'" class="img-list">
        <template v-for="(item, index) in computedList" :key="item.url">
          <div class="img-item" @click="handleViewImg(index)">
            <ATooltip placement="right">
              <img v-lazy="item.url" alt="" />
              <template #title>
                <div class="img-data">
                  <div class="data-item flex">
                    <div class="label">文件名称:</div>
                    <div class="value">{{ item.fileName }}</div>
                  </div>
                  <div class="data-item flex">
                    <div class="label">文件大小:</div>
                    <div class="value">{{ item.size }}</div>
                  </div>
                  <div class="data-item flex">
                    <div class="label">时间:</div>
                    <div class="value">{{ item.time }}</div>
                  </div>
                </div>
              </template>
            </ATooltip>
            <div class="img-desc">{{ item.fileName }}</div>
          </div>
        </template>
      </div>
      <div v-if="showType === 'table'" class="h-full w-full table">
        <Table
          :data-source="computedList"
          :column="columns"
          size="small"
          :is-pagination="false"
          row-key="fileName"
          :scroll="{ y: tableScrollY }"
          class="h-full w-full"
        ></Table>
      </div>
    </div>
    <div class="pagination">
      <APagination
        v-model:current="pageNum"
        v-model:page-size="pageSize"
        show-size-changer
        show-quick-jumper
        :total="total"
        :page-size-options="pageSizeOptions"
        @change="onChange"
      />
    </div>

    <Modal
      v-model:visible="viewImgVisible"
      :title="computedList?.[currentImgViewIndex]?.fileName"
      width="750px"
      height="650px"
      @close="handleViewImgClose"
    >
      <div class="view-img-content" @wheel="handleScroll">
        <img
          ref="imgRef"
          :style="{ transform: ` translate(-50%, -50%) scale(${imgScale}) rotate(${rotate}deg)` }"
          :src="viewImgList[currentImgViewIndex]"
          alt=""
        />
      </div>
      <template #footer>
        <div class="modal-footer">
          <AButton @click="handleRotate('left')">左旋转</AButton>
          <AButton @click="handleRotate('right')">右旋转</AButton>
          <AButton @click="handleScale('plus')">放大</AButton>
          <AButton @click="handleScale('minus')">缩小</AButton>
          <AButton @click="handleImgPreviou">上一张</AButton>
          <AButton @click="handleNext">下一张</AButton>
        </div>
      </template>
    </Modal>
  </div>
</template>

<style lang="scss" scoped>
.aoi-img-page {
  position: relative;
  .show-type {
    display: flex;
    align-items: center;

    .lable {
      margin-right: 8px;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans',
        sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
    }
  }

  .top {
    padding: 5px 25px;
    border-radius: 8px;
    background-color: #fff;
    box-shadow:
      0 1px 2px 0 rgba(0, 0, 0, 0.03),
      0 1px 6px -1px rgba(0, 0, 0, 0.02),
      0 2px 4px 0 rgba(0, 0, 0, 0.02);
    display: flex;
    justify-content: space-between;
    margin: 0 8px;
  }

  .img-content {
    height: calc(100% - 110px);
    background-color: #fff;
    box-shadow:
      0 1px 2px 0 rgba(0, 0, 0, 0.03),
      0 1px 6px -1px rgba(0, 0, 0, 0.02),
      0 2px 4px 0 rgba(0, 0, 0, 0.02);
    padding: 0 8px;
    margin-top: 8px;
    border-radius: 8px;
    overflow-y: auto;
    overflow-x: hidden;

    .img-list {
      padding: 15px;
      display: flex;
      flex-wrap: wrap;
      gap: 10px;

      .img-item {
        width: 80px;
        padding: 10px;
        box-sizing: border-box;

        &:hover {
          background: #f0f9f7 !important;
          // border: 1px solid #ddefeb;
        }

        .img-desc {
          white-space: nowrap;
          /* 强制文本在一行内显示 */
          overflow: hidden;
          /* 隐藏溢出的内容 */
          text-overflow: ellipsis;
          /* 显示省略号 */
          text-align: center;
        }
      }
    }
    // .table {
    //   :deep(.ant-card) {
    //     height: 100%;
    //   }
    // }
  }

  .pagination {
    background-color: #fff;
    box-shadow:
      0 1px 2px 0 rgba(0, 0, 0, 0.03),
      0 1px 6px -1px rgba(0, 0, 0, 0.02),
      0 2px 4px 0 rgba(0, 0, 0, 0.02);
    margin: 0 8px;
    margin-top: 8px;
    border-radius: 8px;
    padding: 10px 10px;
    display: flex;
    justify-content: flex-end;
  }

  // .img-viewer {
  //   width: 100%;
  //   height: 100%;
  //   position: absolute;
  //   top: 0;
  //   left: 0;
  //   background: transparent;
  //   z-index: 997;
  //   .view-img-content {
  //     position: absolute;
  //     left: 50%;
  //     top: 50%;
  //     background: rgb(0 0 0 / 0.85);
  //     z-index: 9999;
  //     height: 650px;
  //     width: 750px;
  //     margin-left: -375px;
  //     margin-top: -325px;
  //     overflow: hidden;
  //     -webkit-box-shadow: 0 0 3px 1px rgba(0, 0, 0, 0.3);
  //     -moz-box-shadow: 0 0 3px 1px rgba(0, 0, 0, 0.3);
  //     box-shadow: 0 0 3px 1px rgba(0, 0, 0, 0.3);
  //     border-radius: 4px;
  //     .header {
  //       height: 45px;
  //       line-height: 45px;
  //       width: 100%;
  //       position: absolute;
  //       z-index: 999;
  //       .preview-title {
  //         text-align: center;
  //         width: 100%;
  //         display: inline-block;
  //         font-size: 16px;
  //         background-color: rgb(0 0 0 / 0.45);
  //         color: #cacaca;
  //         // cursor: all-scroll;
  //       }
  //       .preview_small {
  //         position: absolute;
  //         right: 40px;
  //         top: 0;
  //         width: 45px;
  //         height: 45px;
  //         line-height: 47px;
  //         text-align: center;
  //         color: #d6d6d6;
  //         cursor: pointer;
  //         .iconfont {
  //           font-size: 24px;
  //         }
  //       }
  //       .preview-close {
  //         color: #fff;
  //         cursor: pointer;
  //         position: absolute;
  //         right: 0;
  //         top: 0;
  //         width: 45px;
  //         height: 45px;
  //         line-height: 47px;
  //         text-align: center;
  //         .text-icon {
  //           font-size: 28px;
  //         }
  //       }
  //     }
  //     .preview-body {
  //       position: relative;
  //       height: 100%;
  //       z-index: 99;
  //       padding: 45px 0;
  //       img {
  //         position: absolute;
  //         display: none;
  //         transition: all 200ms;
  //         display: inline-block;
  //         webkit-user-select: none;
  //         -moz-user-select: none;
  //         -ms-user-select: none;
  //         user-select: none;
  //         top: 50%;
  //         left: 50%;
  //         transform: translate(-50%, -50%);
  //         z-index: 1000;
  //       }
  //     }
  //     .preview-toolbar {
  //       position: absolute;
  //       bottom: 0;
  //       width: 250px;
  //       left: 50%;
  //       margin-left: -125px;
  //       height: 45px;
  //       border-radius: 3px;
  //       background-color: rgb(0 0 0 / 0.65);
  //       font-size: 18px;
  //       z-index: 999;
  //       // opacity: 0;
  //       transition: all 1000ms;
  //     }
  //   }
  // }
}

.view-img-content {
  width: 100%;
  height: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  position: relative;
  overflow: hidden;
  img {
    position: absolute;
    top: 50%;
    left: 50%;
    transition: all 200ms;
    transform: translate(-50%, -50%);
    cursor: all-scroll;
  }
}
</style>
